package com.meis.widget.photodrag;

import com.ryan.ohos.extension.event.DispatchHelper;
import com.ryan.ohos.extension.event.impl.ViewGroupHelper;
import com.ryan.ohos.extension.event.interfaces.ViewGroup;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

/**
 * Created by wenshi on 2018/5/18.
 * Description
 */
public class PhotoDragRelativeLayout extends DependentLayout implements Component.TouchEventListener, ViewGroup {
    private ViewGroupHelper impl;
    private PhotoDragDelegate mDragDelegate;
    private boolean mIntercept = true;

    public PhotoDragRelativeLayout(Context context) {
        this(context, null);
    }

    public PhotoDragRelativeLayout(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public PhotoDragRelativeLayout(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init(context);
    }

    private void init(Context context) {
        impl = new ViewGroupHelper(this);
        mDragDelegate = new PhotoDragDelegate(context);
        setTouchEventListener(this);
    }

    /**
     * 设置OnPhotoDragListener
     *
     * @param listener
     */
    public void setDragListener(OnPhotoDragListener listener) {
        mDragDelegate.setDragListener(listener);
    }

    public PhotoDragDelegate getDragDelegate() {
        return mDragDelegate;
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        return DispatchHelper.dispatch(component, touchEvent);
    }

    @Override
    public void requestDisallowInterceptTouchEvent(boolean b) {
        impl.requestDisallowInterceptTouchEvent(b);
    }

    @Override
    public boolean onInterceptTouchEvent(TouchEvent touchEvent) {
        boolean intercept = mDragDelegate.onInterceptTouchEvent(touchEvent);

        if (intercept) {
            requestDisallowInterceptTouchEvent(true);
        }

        return intercept && mIntercept;
    }

    public void setIntercept(boolean intercept) {
        mIntercept = intercept;
    }

    @Override
    public boolean dispatchTouchEvent(TouchEvent touchEvent) {
        return impl.dispatchTouchEvent(touchEvent);
    }

    @Override
    public boolean onTouchEvent(TouchEvent touchEvent) {
        mDragDelegate.onTouchEvent(touchEvent);
        return true;
    }

    @Override
    public boolean isConsumed() {
        return impl.isConsumed();
    }
}
